package com.yjha.huazhubusiness.controller;

/*
 * @author :
 * @date   :2023/8/29 16:33
 * @description : JAVA
 */

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.interfaces.Claim;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import com.github.wxpay.sdk.WXPayUtil;
import com.yjha.huazhubusiness.bean.TbUserInfo;
import com.yjha.huazhubusiness.service.TbUserInfoService;
import com.yjha.huazhubusiness.utils.HttpClientUtil;
import com.yjha.huazhubusiness.utils.JwtUtils;
import com.yjha.huazhubusiness.utils.SendGetUilt;
import com.yjha.huazhubusiness.utils.SignUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;

@CrossOrigin
// @Slf4j
// @Api(tags = "微信授权")
@RestController
@RequestMapping("wx")
public class WxPortalController {
    @Autowired
    private TbUserInfoService tbUserInfoService;
    @Value(value = "${vx.appid}")
    private String appidKey;
    @Value(value = "${vx.secret}")
    private String secretKey;
    /**
     * 请求微信服务对接token验证
     *
     * @param request
     * @param response
     * @throws IOException
     */
    // @ApiOperation("token验证")
    @GetMapping("/auth")
    public void authPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //System.out.println("测试singinat：" + request.getParameter("signature"));
        if (StringUtils.isNotBlank(request.getParameter("signature"))) {
            String signature = request.getParameter("signature");
            String timestamp = request.getParameter("timestamp");
            String nonce = request.getParameter("nonce");
            String echostr = request.getParameter("echostr");
            // log.info("signature[{}], timestamp[{}], nonce[{}], echostr[{}]", signature, timestamp, nonce, echostr);
            if (SignUtil.checkSignature(signature, timestamp, nonce)) {
                // log.info("数据源为微信后台，将echostr[{}]返回！", echostr);
                response.getOutputStream().println(echostr);
            }
        }
    }

    // @ApiOperation("微信签名")
    @GetMapping("jssk")
    public Map jssdk(String url) {
        Map<String, String> map = new HashMap<String, String>();
        String nonceStr = WXPayUtil.generateNonceStr();//随机生产16位字符串，例如：Wm3WZYTPz0wzccnW
        Long s = System.currentTimeMillis() / 1000;//获取时间戳除以千变字符串
        String timeStamp = String.valueOf(s);
        String appId = appidKey;
        String secret = secretKey;
        String url3 = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + secret + "";
        String backData = SendGetUilt.sendGetjssk(url3, "utf-8", 10000);
        // log.info("backData[{}]", backData);
        String accessToken = JSONObject.parseObject(backData).getString("access_token");
        //log.info("获取token[{}]", accessToken);
        String urlStr = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + accessToken + "&type=jsapi";
        //获取jsapiTicket
        String backData2 = SendGetUilt.sendGetjssk(urlStr, "utf-8", 10000);
        //log.info("backData2的值[{}]", accessToken);
        String ticket = JSONObject.parseObject(backData2).getString("ticket");
        try {
            String shaStr = "jsapi_ticket=" + ticket + "&noncestr=" + nonceStr + "&timestamp=" + timeStamp + "&url=" + url;
            MessageDigest mDigest = MessageDigest.getInstance("SHA1");
            byte[] result = mDigest.digest(shaStr.getBytes());
            StringBuffer signature = new StringBuffer();
            for (int i = 0; i < result.length; i++) {
                signature.append(Integer.toString((result[i] & 0xff) + 0x100, 16).substring(1));
            }
            // log.info("nonceStr的值[{}]", nonceStr);
            // log.info("signature的值[{}]", signature.toString());
            map.put("nonceStr", nonceStr);
            map.put("timestamp", timeStamp);
            map.put("signature", signature.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        // log.info("map集合的值：[{}]", map);
        return map;
    }

    // @ApiOperation("获取微信token")
    @GetMapping("getUrl")
    public Map<String, Object> getUrl(@RequestParam String code) {
        // log.info("传入code的值：[{}]", code);
        String appid = appidKey;
        String secret = secretKey;

        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid + "&secret=" + secret + "&code=" + code + "&grant_type=authorization_code";

        try {
            // 创建URL对象
            URL apiUrl = new URL(url);

            // 打开连接
            HttpURLConnection connection = (HttpURLConnection) apiUrl.openConnection();

            // 设置请求方法
            connection.setRequestMethod("GET");

            // 获取响应状态码
            int responseCode = connection.getResponseCode();

            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 读取响应内容
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                StringBuilder response = new StringBuilder();
                String line;

                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }

                reader.close();

                // 解析JSON数据为Map<String, Object>格式
                ObjectMapper mapper = new ObjectMapper();
                Map<String, Object> data = mapper.readValue(response.toString(), new TypeReference<Map<String, Object>>() {
                });
                // log.info("data的值：[{}]", data);
                // 关闭连接
                connection.disconnect();

                // 输出响应内容（JSON数据）
                return data;
            } else {
                Map<String, Object> data = new HashMap<>();
                data.put("请求状态", "失败");
                data.put("响应状态码", responseCode);
                // 关闭连接
                connection.disconnect();
                return data;
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    // @ApiOperation("获取登录token")
    @GetMapping("getToken")
    public String getToken(@RequestParam String code) {
        String token=null;
        // log.info("传入code的值：[{}]", code);
        String appid = appidKey;
        String secret = secretKey;;

        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid + "&secret=" + secret + "&code=" + code + "&grant_type=authorization_code";

        try {
            // 创建URL对象
            URL apiUrl = new URL(url);

            // 打开连接
            HttpURLConnection connection = (HttpURLConnection) apiUrl.openConnection();

            // 设置请求方法
            connection.setRequestMethod("GET");

            // 获取响应状态码
            int responseCode = connection.getResponseCode();

            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 读取响应内容
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                StringBuilder response = new StringBuilder();
                String line;

                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }

                reader.close();

                // 解析JSON数据为Map<String, Object>格式
                ObjectMapper mapper = new ObjectMapper();

                Map<String, Object> data = mapper.readValue(response.toString(), new TypeReference<Map<String, Object>>() {
                });
                // log.info("data的值：[{}]", data);
                // 关闭连接
                connection.disconnect();

                // 输出响应内容（JSON数据）
                token= JwtUtils.getToken(data);

                return token;
            } else {
                // 关闭连接
                connection.disconnect();
                return token;
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return token;
    }

    /**
     * 请求微信服务获取用户信息
     *
     * @param token
     * @param openId
     * @return
     */
    @GetMapping("info")
    public JSONObject getUserInfo(HttpServletRequest request) throws Exception {
        String tokenFromRequest = JwtUtils.getTokenFromRequest(request);
        Map<String, Claim> stringClaimMap = JwtUtils.verifyToken(tokenFromRequest);
        String token = stringClaimMap.get("access_token").asString();
        String openid1 = stringClaimMap.get("openid").toString();
        //请求获取userInfo
        String infoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                "?access_token=" + token +
                "&openid=" + openid1 +
                "&lang=zh_CN";
        JSONObject userInfo = JSON.parseObject(HttpClientUtil.doPost(infoUrl, null));
        // log.info("用户信息：[{}]", userInfo);
        String openid = (String) userInfo.get("openid");
        String nickname = (String) userInfo.get("nickname");
        String headimgurl = (String) userInfo.get("headimgurl");
        TbUserInfo tbUserInfo = new TbUserInfo();
        tbUserInfo.setTbWxuuid(openid);
        tbUserInfo.setTbUsername(nickname);
        tbUserInfo.setTbImage(headimgurl);
        tbUserInfoService.saveTbUserInfo(tbUserInfo);
        return userInfo;
    }
    // /**
    //  * 请求微信服务获取用户信息
    //  *
    //  * @return
    //  */
    // @GetMapping("getUserInfo")
    // public Rest getUserInfo(HttpServletRequest request) {
    //     try {
    //         JSONObject jsonObject=new JSONObject();
    //         String token = request.getHeader("Authorization");//获取请求头中的令牌
    //         if (token==null){
    //             return Rest.err(ErrorTypeEnum.ERROR_401,"身份验证失败,请授权！");
    //         }
    //         Map<String, Claim> map=JwtUtils.verifyToken(token);
    //         String access_token=map.get("access_token").asString();
    //         String openId=map.get("openid").asString();
    //         //请求获取userInfo
    //         String infoUrl = "https://api.weixin.qq.com/sns/userinfo" +
    //                 "?access_token=" + access_token +
    //                 "&openid=" + openId +
    //                 "&lang=zh_CN";
    //         JSONObject userInfo = JSON.parseObject(HttpClientUtil.doPost(infoUrl, null));
    //         //log.info("用户信息：[{}]", userInfo);
    //         jsonObject.put("headimgurl",userInfo.get("headimgurl"));
    //         jsonObject.put("bookedPerson",DigestUtil.md5Hex(String.valueOf(userInfo.get("openid"))));
    //         return Rest.ok("查询成功").setData("userInfo",jsonObject);
    //     }catch (Exception e){
    //         return Rest.err(ErrorTypeEnum.ERROR_401,"身份验证失败,请授权！");
    //     }
    // }
}
